package com.wx.service.impl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.wx.core.process.WxApi;
import com.wx.dao.WxImageReplyMapper;
import com.wx.dao.WxResourceMapper;
import com.wx.entity.SysWxuser;
import com.wx.entity.WxImageReply;
import com.wx.entity.WxImageReplyExample;
import com.wx.entity.WxResource;
import com.wx.entity.WxResourceExample;
import com.wx.flag.KeyWordType;
import com.wx.service.SysWxTokenService;
import com.wx.service.WxImageReplyService;
import com.zyht.common.BaseDao;
import com.zyht.common.BaseServiceImpl;
import com.zyht.common.file.DefaultFilePathPreOperation;
import com.zyht.common.inf.IPreOperation;
import com.zyht.common.util.HttpUtils;

@Service("wxImageReplyService")
public class WxImageReplyServiceImpl extends BaseServiceImpl<WxImageReply, WxImageReplyExample> implements WxImageReplyService {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource
	private WxImageReplyMapper wxImageReplyMapper;
	
	@Resource
	private WxResourceMapper wxResourceMapper;
	
	@Resource
	private SysWxTokenService sysWxTokenService;
	
	@Override
	public BaseDao<WxImageReply, WxImageReplyExample> dao(){

		return wxImageReplyMapper;
	}

	@Override
	public int updateWxImageReplyBean(WxImageReply entity, SysWxuser sysWxUser,String servletContext){
		int result = 0;
		String imagePath = entity.getImagePath();
		if(null!=entity.getId()){
			WxImageReply bean = this.wxImageReplyMapper.selectByPrimaryKey(entity.getId());
			if(null!=imagePath && !bean.getImagePath().equals(imagePath)){
				//更新图片素材
				uploadMaterialAndPersist(entity.getIsForever(), servletContext+entity.getImagePath(), entity.getId(),sysWxUser);
			}
			result = this.wxImageReplyMapper.updateByPrimaryKeySelective(entity);
		}else{
			entity.setCreateTime(new Date());
			entity.setWxid(sysWxUser.getWxid());
			result = this.wxImageReplyMapper.insert(entity);
			if(!StringUtils.isEmpty(imagePath)){
				uploadMaterialAndPersist(entity.getIsForever(), servletContext+entity.getImagePath(), entity.getId(),sysWxUser);
			}
		}
		return result;
	}
	
	//上传永久图片素材
	private void uploadMaterialAndPersist(Integer type, String imagePath, Integer refId, SysWxuser sysWxUser){
		if(null==type||0==type){
			return;
		}
		if(null==sysWxUser){
			logger.error("上传图片到微信素材库异常：".concat("The sysWxuser is unreachable!"));
			return;
		}
		Runnable run = new Runnable() {
			@Override
			public void run(){
				String acToken = sysWxTokenService.getAccessToken(sysWxUser);
				IPreOperation<String> operation = new DefaultFilePathPreOperation();
				operation.preDeal(imagePath);
				String fileName = imagePath.substring(imagePath.lastIndexOf("/")+1);
				FileInputStream fis=null;
				byte[] array = null;
				try{
					fis = new FileInputStream(imagePath);
					array = IOUtils.toByteArray(fis);
				} catch (FileNotFoundException e){
					e.printStackTrace();
					logger.error("图片回复-"+refId+"-文件["+imagePath+"]不存在，或地址错误！");
					return ;
				} catch (IOException e){
					e.printStackTrace();
					logger.error("图片回复-"+refId+"-文件["+imagePath+"]转换byte数组异常！");
					return;
				}finally{
					if(null!=fis){
						try{
							fis.close();
						} catch (IOException e){
							e.printStackTrace();
						}
					}
				}
				//永久素材
				String postUrl = String.format(WxApi.MATERIAL_UPLOAD, acToken);
				ByteArrayPartSource ps = new ByteArrayPartSource(fileName, array);
				Part[] parts = {new FilePart("media", ps), new StringPart("type", "image")};
				Map<String, Object> result = HttpUtils.postFile(postUrl,parts);
				if(null!=result.get("errcode")){
					logger.error("图片回复-".concat(refId.toString()).concat("-上传永久图片素材失败：").concat(result.get("errcode").toString()
							.concat(":").concat(result.get("errmsg").toString())));
					return;
				}
				String mediaId = result.get("media_id").toString();
				String imageWxUrl = result.get("url").toString();
				WxResourceExample example = new WxResourceExample();
				example.createCriteria().andRefTypeEqualTo(KeyWordType.TYPE_IMAGE.getValue()).andRefIdEqualTo(refId);
				List<WxResource> resList = wxResourceMapper.selectByExample(example);
				WxResource resource = new WxResource();
				resource.setMediaId(mediaId);
				resource.setRefId(refId);
				resource.setRefType(KeyWordType.TYPE_IMAGE.getValue());
				resource.setWxImageUrl(imageWxUrl);
				if(null==resList || resList.size()==0){
					wxResourceMapper.insert(resource);
				}else{
					resource.setId(resList.get(0).getId());
					wxResourceMapper.updateByPrimaryKey(resource);
				}
			}
		};
		new Thread(run).start();
	}

	@Override
	public int deleteWxImageReplyBean(Integer id,SysWxuser sysWxUser){
		//删除微信素材中的图片
		Runnable run = new Runnable() {
			@Override
			public void run(){
				String acToken = sysWxTokenService.getAccessToken(sysWxUser);
				WxResourceExample resourceExample = new WxResourceExample();
				resourceExample.createCriteria().andRefIdEqualTo(id).andRefTypeEqualTo(KeyWordType.TYPE_IMAGE.getValue());
				PageHelper.startPage(1,1);
				List<WxResource> list = wxResourceMapper.selectByExample(resourceExample);
				if(list.size()>0){
					WxResource bean = list.get(0);
					String mediaId = bean.getMediaId();
					Map<String, Object> params = new HashMap<>();
					params.put("access_token", acToken);
					params.put("media_id", mediaId);
					String json = JSON.toJSONString(params);
					try{
						String result = HttpUtils.post(WxApi.DEL_MATERIAL,json);
						logger.info("删除微信素材库图片["+id+"]结果是："+result);
					} catch (Exception e){
						e.printStackTrace();
						logger.error("删除微信素材库图片["+id+"]异常："+e.getMessage());
					}
				}
			}
		};
		new Thread(run).start();
		return this.wxImageReplyMapper.deleteByPrimaryKey(id);
	}
}
